package com.lhg.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhg.common.CommonResult;
import com.lhg.entity.Dimension;
import com.lhg.entity.Info;
import com.lhg.entity.Rate;
import com.lhg.entity.User;
import com.lhg.entity.Vo.InfoVo;
import com.lhg.service.InfoService;
import com.lhg.service.MemberService;
import com.lhg.service.UserService;
import com.lhg.utils.AiRecognizeUtil;
import com.lhg.utils.JwtTokenUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private InfoService infoService;
    @Autowired
    private MemberService memberService;

    @GetMapping("/offers")
    public CommonResult<?> getOffers(@RequestHeader("Authorization") String authHeader,
                                     @RequestParam(defaultValue = "1") Integer currentPage,
                                     @RequestParam(defaultValue = "10") Integer size){
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        List<Info> infoList = infoService.selectOffers(foundUser.getId());
        return CommonResult.success(infoList);
    }

    @PostMapping("/dimension/add")
    public CommonResult<?> addDimension(@RequestHeader("Authorization") String authHeader,
                                        @RequestBody Dimension dimension) {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        dimension.setUserId(foundUser.getId());
        memberService.insertDimension(dimension);
        return CommonResult.success("提交成功");
    }

    @GetMapping("/dimension/display")
    public CommonResult<?> displayDimension(@RequestHeader("Authorization") String authHeader){
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        List<Dimension> dimensionList = memberService.selectDimension(foundUser.getId());
        return CommonResult.success(dimensionList);
    }

    @PostMapping("/dimension/edit/{editId}")
    public CommonResult<?> editDimension(@PathVariable Integer editId,
                                         @RequestBody Dimension editForm){
        Dimension dimension = memberService.selectById(editId);
        dimension.setName(editForm.getName());
        dimension.setMaxVal(editForm.getMaxVal());
        memberService.deleteById(editId);
        memberService.insertDimension(dimension);
        return CommonResult.success("编辑成功");
    }

    @DeleteMapping("/dimension/delete/{id}")
    public CommonResult<?> deleteDimension(@PathVariable Integer id){
        memberService.deleteById(id);
        return CommonResult.success("删除成功");
    }

    @GetMapping("/offerRating/{id}")
    public CommonResult<?> offerRate(@PathVariable Integer id){
        List<Rate> rateList = memberService.selectByInfoId(id);
        Map<String,Integer> ratings = new HashMap<String, Integer>();
        for(Rate rate : rateList){
            ratings.put(rate.getName(),rate.getValue());
        }
        return CommonResult.success(ratings);
    }

    @PostMapping("/ratingChange/{infoId}")
    public CommonResult<?> ratingChange(@PathVariable Integer infoId,
                                        @RequestBody Map<String,Integer> ratingForm){

        List<Rate> existRate = memberService.selectByInfoId(infoId);
        if(existRate.size()==0){
            for(String name : ratingForm.keySet()){
                memberService.insertByIdName(infoId, name, ratingForm.get(name));
            }
        }else{
            List<String> existName = new LinkedList<>();
            for(Rate rate : existRate){
                existName.add(rate.getName());
            }
            for(String name : ratingForm.keySet()){
                if(existName.contains(name)){
                    memberService.updateByIdName(infoId, name, ratingForm.get(name));
                }else{
                    memberService.insertByIdName(infoId, name, ratingForm.get(name));
                }
            }
        }
        return CommonResult.success("更新成功");
    }

    @PostMapping("/compareOffers")
    public CommonResult<?> compareOffers(@RequestBody Map<String,List<Integer>> Ids) throws Exception {
        AiRecognizeUtil aiUtil = new AiRecognizeUtil();
        String questionHeader = "我会给你发我待选的几个方案的各个维度打分信息，你需要根据各维度打分信息帮我定量的选择方案，描述定量方法和计算结果，并结合结果给我建议。各个方案各个维度打分信息如下：";
        List<Integer> offerIds = Ids.get("data");
        StringBuilder sb = new StringBuilder();
        for(Integer infoId : offerIds){
            List<Rate> rateList = memberService.selectByInfoId(infoId);
            sb.append("方案"+infoId+": ");
            for(Rate rate : rateList){
                sb.append(rate.toString());
            }
        }
        String content = sb.toString();
        System.out.println(content);
        String response = aiUtil.vivogpt(content,questionHeader);
        ObjectMapper mapper = new ObjectMapper();
        // 解析外部JSON
        JsonNode rootNode = mapper.readTree(response);
        // 获取data字段中的content字段，并去除转义字符
        String contentString = rootNode.get("data").get("content").asText().replaceAll("\\\\n", "").replaceAll("\\\\\"", "\"");
        return CommonResult.success(contentString);
    }
}
